from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth.models import User
from algorithm.models import UserTagMastery, UserComprehensiveLevel, UserProblemRecommendation
from celery import shared_task
from problems.models import Problem
from recommendation.models import SolvedProblem



# @shared_task
# def update_user_data_clock():
#     users = User.objects.all()
#     for user in users:
#         try:
#             DataUpdater.update_data_fetch(user)  # 更新每个用户的数据
#         except Exception as e:
#             print(f"Error updating data for user {user.id}: {e}")


class DataUpdater:
    @classmethod
    def update_data_fetch_user_id(cls, user_id):
        try:
            # 通过 user_id 获取用户实例
            user = User.objects.get(id=user_id)
            # 调用 update_data_fetch 方法进行更新
            cls.update_data_fetch(user)
        except User.DoesNotExist:
            print(f"User with ID {user_id} does not exist.")
        except Exception as e:
            print(f"An error occurred in update_data_fetch_user_id for user ID {user_id}: {e}")

    @classmethod
    def update_data_fetch(cls, user):
        from recommendation_pool.models import UserRecommendationPool
        user_id = user.id
        try:
            # 获取用户已通过的题目
            problems = SolvedProblem.fetch_and_store_user_problems_by_id(user_id)

            # 更新用户数据
            DataUpdater.update_data_normal(user.id, problems)

            # 是独属于fetch函数的调用，需要将用户私下里AC的题目移除pool
            # problems里且在UserRecommendationPool有实例的，则将Pool里的实例删除

            # 获取已通过的题目ID列表
            problem_ids = [problem.problem_number for problem in problems]

            # 查找UserRecommendationPool中属于该用户且在已通过题目中的实例 并 删除
            UserRecommendationPool.objects.filter(user=user, problem__problem_number__in=problem_ids).delete()

        except Exception as e:
            print(f"Error during update for user {user_id}: {e}")

    @classmethod
    def update_data_normal(cls, user_id, problems):
        try:
            for problem in problems:
                SolvedProblem.add_solved_problem(user_id, problem.problem_number)

            UserTagMastery.update_user_tag_mastery_for_problems(user_id=user_id, problems=problems)
            UserComprehensiveLevel.create_or_update_user_level(user_id=user_id)
            UserProblemRecommendation.update_user_problem_recommendation_score(user_id=user_id, problems=problems)

        except Exception as e:
            print(f"Error during update for user {user_id}: {e}")